package it.marcelate.rcp.jdtutil.ui.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

/**
 * 
 * @author demarcom
 *
 * @see http://www.jdg2e.com/ch27.jdt/doc/index.html (The Java Developers Guide to Eclipse # ch. 27)
 * @see http://www.jdg2e.com/jdg2e_CD_for_eclipse321.zip (download examples)
 *
 * TO DO: replacement (SEE ABOVE LINK)
 *
 * {@link http://www.jdg2e.com/jdg2e_CD_for_eclipse321/plug-in_development/examples/com.ibm.jdg2e.jdt/src-extension/com/ibm/jdg2e/jdt/extras/MakeIMemberPrivateAction.java}
 *
 *
 */


public class FindAndReplaceMethodAction extends FindAndReplaceMethodBaseAction {

  private List selectedElements;
  
  @Override
  public void run(IAction action) {
    System.out.println("======> FindAndReplaceMethodAction.run");
    if (selectedElements != null) {
      for (Iterator itSel = selectedElements.iterator(); itSel.hasNext();) {
        Object selected = itSel.next();
        if (selected != null) {
          if (selected instanceof ICompilationUnit) {
            ICompilationUnit cu = (ICompilationUnit)selected;
            super.processCompilationUnit(cu);
          }
        }
      }
    }
  }

  @Override
  public void selectionChanged(IAction action, ISelection selection) {
    if (selection != null) {
      if (selection instanceof IStructuredSelection) {
        IStructuredSelection sel = (IStructuredSelection)selection;
        if (!sel.isEmpty()) {
          selectedElements = new ArrayList();
          for (Iterator it = sel.iterator(); it.hasNext();) {
            selectedElements.add(it.next());
          }
        }
        
      } else if (selection instanceof ITextSelection) {
        ITextSelection sel = (ITextSelection)selection;
        System.out.println("Text selected is " + sel.getText());
        
        IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
        IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
        selectedElements = new ArrayList();
        selectedElements.add(manager.getWorkingCopy(editor.getEditorInput()));
        
      }
    }
  }
  
  @Override
  public void dispose() {

  }

  @Override
  public void init(IWorkbenchWindow window) {

  }

  

}
